package com.yc.multiple.jpa.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

@Configuration
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryPaycenter",
        transactionManagerRef = "transactionManagerPaycenter",
        basePackages = {"com.yc.multiple.jpa.dao.paycenter"}
)
public class PaycenterDataSourceConfig {

    @Autowired
    private JpaProperties jpaProperties;

    @Bean
    @Primary
    @ConfigurationProperties("spring.datasource.paycenter")
    public DataSource paycenterDataSource(){
        return new HikariDataSource();
    }

    @Primary
    @Bean(name = "entityManagerFactoryPaycenter")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPaycenter(EntityManagerFactoryBuilder builder) {
        LocalContainerEntityManagerFactoryBean entityManagerFactory = builder
                .dataSource(paycenterDataSource())
                //设置实体类所在位置
                .packages("com.yc.multiple.jpa.bean.paycenter")
                .persistenceUnit("paycenterPersistenceUnit")
                .properties(jpaProperties.getProperties())
                .build();
        return entityManagerFactory;
    }

    @Primary
    @Bean(name = "transactionManagerPaycenter")
    public PlatformTransactionManager transactionManagerPaycenter(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryPaycenter(builder).getObject());
    }
}
